package com.zhx.dao.impl;

import com.zhx.dao.UserDao;
import com.zhx.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @program: web-springboot
 * @author: zhx
 * @create: 2021-05-22 00:32
 **/
@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    JdbcTemplate jdbcTemplate;

    private String FIND_USER_COUNT="SELECT COUNT(*) FROM USER WHERE USERNAME=? AND PASSWORD=?";
    private String FIND_USER_USERNAME="SELECT * FROM USER WHERE USERNAME=?";

    /**
     * 得到匹配用户的个数
     * @param username
     * @param password
     * @return
     */
    @Override
    public int getMatchCount(String username,String password){
        Integer count = jdbcTemplate.queryForObject(FIND_USER_COUNT, new Object[]{username, password}, Integer.class);
        return count;
    }

    /**
     * 根据用户名查找用户信息
     * @param username
     * @return
     */
    @Override
    public User findUserbyName(String username){
        final User[] user = {null};
        jdbcTemplate.query(FIND_USER_USERNAME, new Object[]{username}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                user[0] = new User();
                user[0].setId(resultSet.getInt(1));
                user[0].setUsername(resultSet.getString(2));
                user[0].setPassword(resultSet.getString(3));
            }
        });
        return user[0];
    }
}
